import 'package:flutter/material.dart';
import 'package:get/get.dart';

/// 完全自定义的引导组件 - 不依赖任何第三方库
/// 支持高亮指定区域、显示引导文案、步骤切换等功能
class CustomGuideWidget extends StatefulWidget {
  /// 引导步骤列表
  final List<GuideStep> steps;
  
  /// 完成回调
  final VoidCallback onFinish;
  
  /// 跳过回调
  final VoidCallback? onSkip;

  const CustomGuideWidget({
    super.key,
    required this.steps,
    required this.onFinish,
    this.onSkip,
  });

  @override
  State<CustomGuideWidget> createState() => _CustomGuideWidgetState();
}

class _CustomGuideWidgetState extends State<CustomGuideWidget>
    with SingleTickerProviderStateMixin {
  int _currentStep = 0;
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeIn),
    );

    _animationController.forward();
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  void _nextStep() {
    if (_currentStep < widget.steps.length - 1) {
      setState(() {
        _currentStep++;
      });
      _animationController.reset();
      _animationController.forward();
    } else {
      _finish();
    }
  }

  void _previousStep() {
    if (_currentStep > 0) {
      setState(() {
        _currentStep--;
      });
      _animationController.reset();
      _animationController.forward();
    }
  }

  void _finish() {
    widget.onFinish();
    Get.back();
  }

  void _skip() {
    widget.onSkip?.call();
    Get.back();
  }

  @override
  Widget build(BuildContext context) {
    final step = widget.steps[_currentStep];
    final size = MediaQuery.of(context).size;

    return Material(
      color: Colors.transparent,
      child: Stack(
        children: [
          // 半透明黑色遮罩
          GestureDetector(
            onTap: () {}, // 防止点击穿透
            child: Container(
              width: size.width,
              height: size.height,
              color: Colors.black.withOpacity(0.75),
            ),
          ),

          // 高亮区域（如果有指定位置）
          if (step.targetRect != null) _buildHighlightArea(step.targetRect!),

          // 引导内容
          Positioned(
            left: step.contentPosition.dx,
            top: step.contentPosition.dy,
            child: FadeTransition(
              opacity: _fadeAnimation,
              child: _buildGuideContent(step, size),
            ),
          ),

          // 跳过按钮
          Positioned(
            top: MediaQuery.of(context).padding.top + 16,
            right: 16,
            child: TextButton(
              onPressed: _skip,
              style: TextButton.styleFrom(
                backgroundColor: Colors.white.withOpacity(0.2),
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              ),
              child: const Text(
                '跳过',
                style: TextStyle(color: Colors.white, fontSize: 14),
              ),
            ),
          ),

          // 进度指示器
          Positioned(
            bottom: 80,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(
                widget.steps.length,
                (index) => Container(
                  margin: const EdgeInsets.symmetric(horizontal: 4),
                  width: index == _currentStep ? 24 : 8,
                  height: 8,
                  decoration: BoxDecoration(
                    color: index == _currentStep
                        ? Colors.white
                        : Colors.white.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建高亮区域
  Widget _buildHighlightArea(Rect rect) {
    return Positioned(
      left: rect.left - 8,
      top: rect.top - 8,
      child: Container(
        width: rect.width + 16,
        height: rect.height + 16,
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(
            color: Colors.white.withOpacity(0.5),
            width: 2,
          ),
          boxShadow: [
            BoxShadow(
              color: Colors.white.withOpacity(0.3),
              blurRadius: 20,
              spreadRadius: 5,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建引导内容
  Widget _buildGuideContent(GuideStep step, Size screenSize) {
    return Container(
      constraints: BoxConstraints(
        maxWidth: screenSize.width * 0.8,
      ),
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.3),
            blurRadius: 20,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 图标
          if (step.icon != null)
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: const Color(0xFF6366F1).withOpacity(0.1),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                step.icon,
                color: const Color(0xFF6366F1),
                size: 32,
              ),
            ),
          
          if (step.icon != null) const SizedBox(height: 16),

          // 标题
          Text(
            step.title,
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: Color(0xFF1F2937),
            ),
          ),

          const SizedBox(height: 12),

          // 描述
          Text(
            step.description,
            style: const TextStyle(
              fontSize: 15,
              color: Color(0xFF6B7280),
              height: 1.5,
            ),
          ),

          const SizedBox(height: 20),

          // 按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // 上一步按钮
              if (_currentStep > 0)
                TextButton(
                  onPressed: _previousStep,
                  child: const Text('上一步'),
                )
              else
                const SizedBox.shrink(),

              // 下一步/完成按钮
              ElevatedButton(
                onPressed: _nextStep,
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF6366F1),
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 32,
                    vertical: 12,
                  ),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
                ),
                child: Text(
                  _currentStep == widget.steps.length - 1 ? '完成' : '下一步',
                  style: const TextStyle(
                    fontSize: 15,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

/// 引导步骤数据模型
class GuideStep {
  /// 标题
  final String title;
  
  /// 描述文字
  final String description;
  
  /// 图标（可选）
  final IconData? icon;
  
  /// 引导内容的显示位置
  final Offset contentPosition;
  
  /// 需要高亮的目标区域（可选）
  final Rect? targetRect;

  GuideStep({
    required this.title,
    required this.description,
    this.icon,
    required this.contentPosition,
    this.targetRect,
  });
}

/// 显示自定义引导的便捷方法
void showCustomGuide(
  BuildContext context, {
  required List<GuideStep> steps,
  required VoidCallback onFinish,
  VoidCallback? onSkip,
}) {
  showDialog(
    context: context,
    barrierDismissible: false,
    barrierColor: Colors.transparent,
    builder: (context) => CustomGuideWidget(
      steps: steps,
      onFinish: onFinish,
      onSkip: onSkip,
    ),
  );
}

/// 根据 GlobalKey 获取控件的位置和大小
Rect? getWidgetBounds(GlobalKey key) {
  final RenderBox? renderBox = key.currentContext?.findRenderObject() as RenderBox?;
  if (renderBox == null) return null;
  
  final position = renderBox.localToGlobal(Offset.zero);
  final size = renderBox.size;
  
  return Rect.fromLTWH(position.dx, position.dy, size.width, size.height);
}

